package main

import (
	"encoding/json"
	"fmt"
	"io"
	"keep_learning_go_2023/week2/server"
	"keep_learning_go_2023/week2/vo"
	"net/http"
)

// 首页返回的环境
func home(res http.ResponseWriter, req *http.Request) {
	res.Write([]byte("环境访问，这个是首页！"))
}

// 从http请求中获取body
func readBody(res http.ResponseWriter, req *http.Request) {

	//这里只能读取一次Body的数据
	body, err := io.ReadAll(req.Body)
	if err != nil {
		fmt.Fprintf(res, "read body has error : %v", err)
	}

	fmt.Fprintf(res, "read body is : %s", string(body))

}

// 从http请求URI中获取获取参数
func readQuery(res http.ResponseWriter, req *http.Request) {
	values := req.URL.Query()
	for key, value := range values {
		fmt.Fprintf(res, "server get params is : key-> %s, value-> %s \n", key, value)
	}
}

// 获取http请求的header信息
func readHeader(res http.ResponseWriter, req *http.Request) {
	header := req.Header
	headerJson, _ := json.Marshal(header)
	fmt.Fprintf(res, "the header is : %v", string(headerJson))
}

// 模仿java 中的controller,对请求和返回值进行封装，
func signUp(res http.ResponseWriter, req *http.Request) {

	context := server.HttpContextFactory(res, req)
	signUp := &vo.SignUp{}
	err := context.ReadJson(signUp)
	if err != nil {
		message := err.Error()
		context.WriteJson(server.INTERNAL_ERROR, message, nil)
		return
	}

	message := "success"
	//经过业务逻辑处理后得到的结果
	result := signUp
	context.WriteJson(server.OK, message, result)

}

// 模仿java 中的controller,通过上下文对请求进行操作
func signUpWithContext(context *server.HttpContext) {

	signUp := &vo.SignUp{}
	err := context.ReadJson(signUp)
	if err != nil {
		message := err.Error()
		context.WriteJson(server.INTERNAL_ERROR, message, nil)
		return
	}

	message := "success"
	//经过业务逻辑处理后得到的结果
	result := signUp
	context.WriteJson(server.OK, message, result)

}

// http服务的入口，从最简单的http服务开始写
func main() {
	//api接口
	//http.HandleFunc("/",home)
	//http.HandleFunc("/readBody",readBody)
	//http.HandleFunc("/readQuery",readQuery)
	//http.HandleFunc("/readHeader",readHeader)
	//
	////http服务启动方法
	////这里的第一个参数需要带冒号，否则会有异常出现
	//if err := http.ListenAndServe(":8080",nil) ; err != nil {
	//	panic(err)
	//}
	myServer := server.HttpServletFactory("myserver")
	myServer.Route("/", home)
	myServer.Route("/readBody", readBody)
	myServer.Route("/readQuery", readQuery)
	myServer.Route("/readHeader", readHeader)
	myServer.Route("/signUp", signUp)
	myServer.RouteWithContext("/signUpWithContext", signUpWithContext)

	myServer.Start(":8080")

}
